import {
  getNumSerialNumber,
  getCharSerialNumber,
  getRandomSerialNumber,
  getDateSerialNumber
} from '@renderer/utils/SerialNumberUtils'
import useSerialNumberFormStore from '@renderer/store/Form/SerialNumberFormStore'

// 位置 fn
let positionFn: (tableDataItem: ITableDataItem, insertValue: string) => void

export default function useSerialNumberTransfer(
  callback: () => ITableDataItem[]
) {
  const serialNumberTransfer = () => {
    const {
      serialNumberEnable,
      serialNumberOnly,
      serialNumberPosition,
      serialNumberType,
      serialNumbeAfterCharacter,
      serialNumberStart,
      serialNumberStep,
      serialNumberDigit,
      serialNumberCharStart,
      serialNumberChartStep,
      serialNumberRandomRule,
      serialNumberRandomChartCount,
      serialNumberDateType,
      serialNumberDateFormat
    } = useSerialNumberFormStore()

    // 启用编号设置
    if (!serialNumberEnable) return

    // 仅使用编号作为文件名
    if (serialNumberOnly) {
      positionFn = (tableDataItem, insertValue) => {
        tableDataItem.newest.name = insertValue
      }
    } else {
      if (serialNumberPosition === '0') {
        // 开头
        positionFn = (tableDataItem, insertValue) => {
          tableDataItem.newest.name = insertValue + tableDataItem.newest.name
        }
      } else if (serialNumberPosition === '1') {
        // 末尾
        positionFn = (tableDataItem, insertValue) => {
          tableDataItem.newest.name = tableDataItem.newest.name + insertValue
        }
      } else if (serialNumberPosition === '2') {
        // 自定义
        positionFn = (tableDataItem, insertValue) => {
          const { name } = tableDataItem.newest
          const arr = name.split('')
          arr.splice(serialNumbeAfterCharacter, 0, insertValue)
          tableDataItem.newest.name = arr.join('')
        }
      }
    }

    let getValue: (item: ITableDataItem) => string

    // 数字
    if (serialNumberType === '0') {
      // 获取数字类型的编号
      const { init, get } = getNumSerialNumber(
        serialNumberStep,
        serialNumberDigit
      )
      // 初始化起始值
      init(serialNumberStart)
      getValue = get
    } else if (serialNumberType === '1') {
      // 字母
      const { get } = getCharSerialNumber(
        serialNumberCharStart,
        serialNumberChartStep
      )
      getValue = get
    } else if (serialNumberType === '2') {
      // 随机字符
      const { get } = getRandomSerialNumber(
        serialNumberRandomRule,
        serialNumberRandomChartCount
      )

      getValue = get
    } else if (serialNumberType === '3') {
      // 时间
      const { get } = getDateSerialNumber(
        serialNumberDateType,
        serialNumberDateFormat
      )

      getValue = get
    }

    callback().forEach((item) => {
      const value = getValue(item)
      positionFn(item, value)
    })
  }

  return {
    serialNumberTransfer
  }
}
